﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WindowsFormsApplication1;
using System.Net;
using System.IO;
using mshtml;
using DeathByCaptcha;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace KeepSummerRolling
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            comboBox1.Items.Add("Manual");
            comboBox1.Items.Add("Decaptcher");
            comboBox1.Items.Add("DBC");
            webBrowser1.ScriptErrorsSuppressed = true;
            initializeSettings();
        }


        public void saveSettings()
        {
            KeepSummerRolling.Properties.Settings.Default.FirstName = txtFName.Text;
            KeepSummerRolling.Properties.Settings.Default.LastName = txtLName.Text;
            KeepSummerRolling.Properties.Settings.Default.Address = txtAddress.Text;
            KeepSummerRolling.Properties.Settings.Default.City = txtCity.Text;
            KeepSummerRolling.Properties.Settings.Default.State = txtState.Text;

            KeepSummerRolling.Properties.Settings.Default.Catchall = txtEmail.Text;
            KeepSummerRolling.Properties.Settings.Default.Zip = txtZip.Text;
            KeepSummerRolling.Properties.Settings.Default.Vin = txtVin.Text;
            KeepSummerRolling.Properties.Settings.Default.Password = txtPass.Text;

            KeepSummerRolling.Properties.Settings.Default.Save();
        }

        public void initializeSettings()
        {
            txtFName.Text = KeepSummerRolling.Properties.Settings.Default.FirstName;
            txtLName.Text =  KeepSummerRolling.Properties.Settings.Default.LastName ;
            txtAddress.Text = KeepSummerRolling.Properties.Settings.Default.Address ;
            txtCity.Text = KeepSummerRolling.Properties.Settings.Default.City ;
            txtState.Text = KeepSummerRolling.Properties.Settings.Default.State ;

            txtEmail.Text = KeepSummerRolling.Properties.Settings.Default.Catchall ;
            txtZip.Text = KeepSummerRolling.Properties.Settings.Default.Zip ;
            txtVin.Text = KeepSummerRolling.Properties.Settings.Default.Vin;
            txtPass.Text = KeepSummerRolling.Properties.Settings.Default.Password;
        }


        private String setCheckDigit(String vin)
        {
            if (vin.Length != 17)
            {
                
                return null;
            }
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                try
                {
                    int num = Convert.ToInt32("" + vin[i]);
                    sum += (num * posValue[i]);

                }
                catch (System.Exception )
                {
                    int num = 0 ;
                    switch (vin[i])
                    {
                        case 'A': 
                            num = A;
                            break;
                        case 'B':
                            num = B;
                            break;
                        case 'C':
                            num = C;
                            break;
                        case 'D':
                            num = D;
                            break;
                        case 'E':
                            num = E;
                            break;
                        case 'F':
                            num = F;
                            break;
                        case 'G':
                            num = G;
                            break;
                        case 'H':
                            num = H;
                            break;
                        case 'J':
                            num = J;
                            break;
                        case 'K':
                            num = K;
                            break;
                        case 'L':
                            num = L;
                            break;
                        case 'M':
                            num = M;
                            break;
                        case 'N':
                            num = N;
                            break;
                        case 'P':
                            num = P;
                            break;
                        case 'R':
                            num = R;
                            break;
                        case 'S':
                            num = S;
                            break;
                        case 'T':
                            num = T;
                            break;
                        case 'U':
                            num = U;
                            break;
                        case 'V':
                            num = V;
                            break;
                        case 'W':
                            num = W;
                            break;
                        case 'X':
                            num = X;
                            break;
                        case 'Y':
                            num = Y;
                            break;
                        case 'Z':
                            num = Z;
                            break;
                      }

                    sum += (num * posValue[i]);
                }
            }
            int checkNum = sum % 11;
            String result = vin;
            if (checkNum == 10)
            {
                result = result.Substring(0, 8) +  'X' + result.Substring(9, 8);
            }
            else
            {
                result = result.Substring(0, 8) + checkNum + result.Substring(9, 8);
            }
            
            return result;
        }


        public const int A = 1, B = 2, C = 3, D = 4, E = 5, F = 6, G = 7, H = 8;
        public const int J = 1, K = 2, L = 3, M = 4, N = 5, P = 7, R = 9;
        public const int S = 2, T = 3, U = 4, V = 5, W = 6, X = 7, Y = 8, Z = 9;
        public int[] posValue = { 8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2 };

        private const int INTERNET_OPTION_END_BROWSER_SESSION = 42;

        [DllImport("wininet.dll", SetLastError = true)]
        private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);


        private void clearCookies()
        {
            string[] theCookies = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Cookies));



            foreach (string currentFile in theCookies)
            {
                try
                {
                    System.IO.File.Delete(currentFile);
                }
                catch (System.Exception) { }

            }
            InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0);

        }

        private void start()
        {
            readUserNames();
            clearCookies();
            nextVin = true;
            nextForm1 = false;
            nextForm2 = false;
            nextLose = false;
            webBrowser1.Navigate("http://www.keepsummerrolling.com/register");
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            saveSettings();
            start();
        }
        bool nextVin = false;
        bool nextForm1 = false;
        bool nextForm2 = false;
        bool nextLose = false;
        bool nextLogin = false;
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
           
            if (webBrowser1.DocumentText.Contains("<form method=\"post\" type=\"input\" action=\"contest-entry-form-01\" id=\"enterpin\">") && nextVin)
            {
                 nextVin = false;
                 nextForm1 = true;
                 nextForm2 = false;
                 nextLose = false;
                acntWritten = false;
                Random rand = new Random();
                vin = setCheckDigit(txtVin.Text.Substring(0, 11) + rand.Next(100000, 999999));
                webBrowser1.Document.GetElementsByTagName("input")[0].SetAttribute("value", vin);
                webBrowser1.Document.GetElementsByTagName("input")[1].InvokeMember("Click");
            }
            else if (webBrowser1.DocumentText.Contains("PART 1 of 2"))
            {
                nextVin = false;
                nextForm1 = false;
                nextForm2 = true;
                nextLose = false;
                email = getCatchallEmail(txtEmail.Text);
                webBrowser1.Document.GetElementById("regemail").SetAttribute("value", email);
                webBrowser1.Document.GetElementById("regconfirmemail").SetAttribute("value", email);
                webBrowser1.Document.GetElementById("regpass").SetAttribute("value", txtPass.Text);
                webBrowser1.Document.GetElementById("regconfirmpass").SetAttribute("value", txtPass.Text);
                webBrowser1.Document.GetElementsByTagName("input")[5].InvokeMember("Click");
                webBrowser1.Document.GetElementsByTagName("input")[6].InvokeMember("Click");
                HtmlElementCollection imgs = webBrowser1.Document.GetElementsByTagName("img");
                int i = 0;
                /*while (!imgs[i].GetAttribute("src").Contains("http://www.google.com/recaptcha/api/image?c=") && i < imgs.Count)
                {
                    i++;
                }*/
                    String pictureUrl = webBrowser1.Document.GetElementsByTagName("img")[i].GetAttribute("src");
                    //webBrowser1.Document.GetElementById("recaptcha_response_field").AttachEventHandler("onfocus", badCaptcha);
                    if (comboBox1.Text.Equals("Manual"))
                    {
                       /* Form2 cap = new Form2();
                        cap.pictureBox1.Image = getImage(pictureUrl);
                        cap.ShowDialog();
                        webBrowser1.Document.GetElementById("recaptcha_response_field").SetAttribute("value", cap.txtValue.Text);*/
                    }
                    if (comboBox1.Text.Equals("Decaptcher"))
                    {
                        SaveCaptchaImage();
                        decap = new Decaptcher(textBoxDecaptcherUser.Text, textBoxDecaptcherPass.Text);
                       
                        lastCap = decap.GetCaptchaSolved(captchaBmp);
                        String answer;
                        try
                        {
                            answer = lastCap.Text;
                        }
                        catch (System.Exception)
                        {
                            answer = "";
                        }
                    
                        webBrowser1.Document.GetElementById("recaptcha_response_field").SetAttribute("value", answer);
                    }
                    if (comboBox1.Text.Equals("DBC"))
                    {
                        
                        
                            Client clientDBC = (Client)new SocketClient(textBoxDecaptcherUser.Text, textBoxDecaptcherPass.Text);

                            SaveCaptchaImage();
                            MemoryStream ms = new MemoryStream();
                            captchaBmp.Save(ms, ImageFormat.Bmp);
                            byte[] bitmapData = ms.ToArray();

                            captcha = clientDBC.Decode(bitmapData, Client.DefaultTimeout);
                            if (captcha != null)
                                webBrowser1.Document.GetElementById("recaptcha_response_field").SetAttribute("value", captcha.Text);
                        
                        //ch (System.Exception)
                                                //    Console.WriteLine("Exception in DBC code.");
                        //}
                    }
                    webBrowser1.Document.GetElementById("regconfirmpass").Focus();
                    webBrowser1.Document.GetElementsByTagName("input")[10].InvokeMember("Click");
                    
                
            }
            else if (webBrowser1.DocumentText.Contains("PART 2 of 2") && nextForm2)
            {
                nextVin = false;
                nextForm1 = false;
                nextForm2 = false;
                nextLose = true;
                badCapCount = 0;
                webBrowser1.Document.GetElementsByTagName("input")[1].SetAttribute("value", txtFName.Text);
                webBrowser1.Document.GetElementsByTagName("input")[2].SetAttribute("value", txtLName.Text);
                webBrowser1.Document.GetElementsByTagName("input")[3].SetAttribute("value", txtAddress.Text);
                webBrowser1.Document.GetElementsByTagName("input")[5].SetAttribute("value", txtCity.Text);
                webBrowser1.Document.GetElementById("states").SetAttribute("value", txtState.Text);
                webBrowser1.Document.GetElementsByTagName("input")[6].SetAttribute("value", txtZip.Text);
                webBrowser1.Document.GetElementsByTagName("input")[7].SetAttribute("value", txtPhone.Text);
                webBrowser1.Document.GetElementsByTagName("input")[14].InvokeMember("Click");
            }
            else if (webBrowser1.DocumentText.Contains("We're sorry, but you are not an Instant Winner of a Nissan Maintenance+Plus") && nextLose)
            {
                nextVin = true;
                nextForm1 = false;
                nextForm2 = false;
                nextLose = false;
                if (!fileAccounts)
                {
                    label2.Text = "Status: Lost (new acnt).";
                    if (!acntWritten)
                    {
                        acntWritten = true;
                        System.IO.StreamWriter acntFile = File.AppendText("KSR-Accounts.txt");
                        acntFile.WriteLine(email + "|" + txtPass.Text + "|" + txtFName.Text + "|" + txtLName.Text + "|" + txtAddress.Text + "|" + vin);
                        acntFile.Close();
                        // MessageBox.Show(email + "|" + txtPass.Text + "|" + txtFName.Text + "|" + txtLName.Text + "|" + txtAddress.Text + "|" + vin);
                    }
                    lostCount++;
                    clearCookies();
                    webBrowser1.Navigate("http://www.keepsummerrolling.com/register");
                }
                else
                {
                    label2.Text = "Status: Lost (file acnt).";
                    nextLose = false;
                    nextLogin = true;
                    lostCount++;
                    label1.Text = "Lost: " + lostCount;
                    clearCookies();

                    nextLogin = true;
                    nextLose = false;
                    webBrowser1.Navigate("http://www.keepsummerrolling.com/login");
                    
                    
                }
                
            }
            else if (webBrowser1.DocumentText.Contains("Thank you for your interest in the Nissan Keep Summer Rolling Service Sweepstakes. You can re-enter daily for another chance to win the Nissan of your choice, weekly prizes of two-year Nissan Maintenance+Plus") && nextLogin)
            {
                nextLogin = false;
                nextLose = true;

                if (!accountsFile.EndOfStream)
                {
                    label2.Text = "Status: Next account.";
                    String account = accountsFile.ReadLine();
                    int i1 = account.IndexOf("|");
                    int i2 = account.IndexOf("|", i1 + 1);
                    int i3 = account.IndexOf("|", i2 + 1);

                    webBrowser1.Document.GetElementById("userin").SetAttribute("value", account.Substring(0, i1));
                    webBrowser1.Document.GetElementById("passin").SetAttribute("value", account.Substring(i1 + 1, i2 - (i1 + 1)));
                    webBrowser1.Document.GetElementById("formsubmit").InvokeMember("Click");
                }
                else
                {
                    label2.Text = "Status: Done with accounts.";
                    timer1.Stop();
                    start();
                }
                
            }
            else if (nextLose && (webBrowser1.Document.Body.InnerHtml.Contains("Each time you re-enter the Sweepstakes") ||webBrowser1.Document.Body.InnerHtml.Contains("The password you have entered does not match your username")))
            {
                nextLose = false;
                nextLogin = true;
                label2.Text = "Status: already entered today.";
                clearCookies();
                timer1.Stop();
                webBrowser1.Navigate("http://www.keepsummerrolling.com/login");
            }
            else if (nextLose && !webBrowser1.DocumentText.Contains("Thank you for your interest in the Nissan Keep Summer Rolling Service Sweepstakes. You can re-enter daily for another chance to win the Nissan of your choice, weekly prizes of two-year Nissan Maintenance+Plus"))
            {
                timer1.Stop();
                label2.Text = "Status: Won!";
                System.IO.StreamWriter writer = File.AppendText("win-time.txt");
                DateTime CurrTime = DateTime.Now;
                string time = CurrTime.Hour + ":" + CurrTime.Minute + ":" + CurrTime.Second + "." + CurrTime.Millisecond;
                writer.WriteLine(email + "|" + CurrTime.Hour + ":" + CurrTime.Minute + ":" + CurrTime.Second + "." + CurrTime.Millisecond);
                writer.Close();
                MessageBox.Show("winnar?!?!? at time : " + time);
            }
        }

        void badCaptcha(object sender, EventArgs e)
        {

            badCapCount++;
            if (badCapCount == 3)
                return;
            HtmlElementCollection imgs = webBrowser1.Document.GetElementsByTagName("img");
            int i = 0;
            while (!imgs[i].GetAttribute("src").Contains("http://www.google.com/recaptcha/api/image?c=") && i < imgs.Count)
            {
                i++;
            }
            String pictureUrl = webBrowser1.Document.GetElementsByTagName("img")[i].GetAttribute("src");
            webBrowser1.Document.GetElementById("recaptcha_response_field").AttachEventHandler("onfocus", badCaptcha);
            if (comboBox1.Text.Equals("Manual"))
            {
                Form2 cap = new Form2();
                cap.pictureBox1.Image = getImage(pictureUrl);
                cap.ShowDialog();
                webBrowser1.Document.GetElementById("recaptcha_response_field").SetAttribute("value", cap.txtValue.Text);
            }
			if (comboBox1.Text.Equals("Decaptcher"))
            {
                        SaveCaptchaImage();
                        decap = new Decaptcher(textBoxDecaptcherUser.Text, textBoxDecaptcherPass.Text);
                     
                        lastCap = decap.GetCaptchaSolved(captchaBmp);
                        String answer;
                        try
                        {
                             answer = lastCap.Text;
                        }
                        catch (System.Exception)
                        {
                             answer = "";
                        }
                      
                webBrowser1.Document.GetElementById("recaptcha_response_field").SetAttribute("value", answer);
            }
            if (comboBox1.Text.Equals("DBC"))
            {
                
                
                    Client clientDBC = (Client)new SocketClient(textBoxDecaptcherUser.Text, textBoxDecaptcherPass.Text);
                    if (captcha != null)
                        clientDBC.Report(captcha);
                    SaveCaptchaImage();
                    MemoryStream ms = new MemoryStream();
                    captchaBmp.Save(ms, ImageFormat.Bmp);
                    byte[] bitmapData = ms.ToArray();

                    captcha = clientDBC.Decode(bitmapData, Client.DefaultTimeout);
                    if (captcha != null)
                        webBrowser1.Document.GetElementById("recaptcha_response_field").SetAttribute("value", captcha.Text);
                
                
                
                //    Console.WriteLine("DBC code Exception.");

                
            }
            webBrowser1.Document.GetElementById("regconfirmpass").Focus();
            webBrowser1.Document.GetElementsByTagName("input")[10].InvokeMember("Click");
        }
        Captcha captcha;

        private void SaveCaptchaImage()
        {
            IHTMLDocument2 doc = (IHTMLDocument2)webBrowser1.Document.DomDocument;
            IHTMLControlRange imgRange = (IHTMLControlRange)((HTMLBody)doc.body).createControlRange();

            foreach (IHTMLImgElement img in doc.images)
            {
                //Change "GenerateCaptcha.aspx?" to whatever the captcha file might be for example "image.aspx?" or "captchaimage.jpg"
                if (img.nameProp.Contains("image?c="))
                {
                    imgRange.add((IHTMLControlElement)img);

                    object a = Clipboard.GetDataObject();

                    imgRange.execCommand("Copy", false, null);
                    captchaBmp = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap);
                    Clipboard.SetDataObject(a, false, 5, 100);

                    break;
                }
            }
        }
		
		Bitmap captchaBmp;
        String lastCaptcha;
        DecaptcherResult lastCap;
        private int badCapCount = 0;
        public int lostCount = 0;

        public Image getImage(String url)
        {
            //Create a webresponse variable and an image variable
            WebResponse result = null;
            Image rImage = null;
            //Encase code in a try statement in case it times out or gets an error
            //Otherwise it would stop the program
            try
            {
                //Create a webrequest for the url
                WebRequest request = WebRequest.Create(url);
                //The image will be in bytes
                byte[] rBytes;

                //Get the content from the webrequest
                result = request.GetResponse();
                //Get the stream from the response
                Stream rStream = result.GetResponseStream();

                //Read the bytes from the stream
                using (BinaryReader br = new BinaryReader(rStream))
                {
                    //You need to have more bytes than the stream
                    rBytes = br.ReadBytes(10000000);
                    //Close the reader
                    br.Close();
                }
                //Close the response object
                result.Close();

                //Convert the bytes into an image
                using (MemoryStream imageStream = new MemoryStream(rBytes, 0, rBytes.Length))
                {
                    //Write the bytes into an memory stream
                    imageStream.Write(rBytes, 0, rBytes.Length);
                    //Put the memory stream into the image
                    rImage = Image.FromStream(imageStream, true);
                    //Close the stream
                    imageStream.Close();
                }
            }
            //This catches any error, if you want to know what the error is you can do something like
            //catch (Exception e) { Console.WriteLine(e.Message); }
            catch { }
            finally
            {
                if (result != null) result.Close();
            }
            //Return the image to where ever it was called from
            return rImage;
        }

        private String getCatchallEmail(String domain)
        {
            Random randomInt = new Random();
            if (domain.Equals(""))
            {
                int dom = randomInt.Next(0, 6);
                switch (dom)
                {
                    case 0:
                        domain = "@gmail.com";
                        break;
                    case 1:
                        domain = "@yahoo.com";
                        break;
                    case 2:
                        domain = "@hotmail.com";
                        break;
                    case 3:
                        domain = "@sbcglobal.net";
                        break;
                    case 4:
                        domain = "@live.com";
                        break;
                    case 5:
                        domain = "@ymail.com";
                        break;
                    case 6:
                        domain = "@rocketmail.com";
                        break;

                }

            }

            int sel = randomInt.Next(0, 9999);
            int num = randomInt.Next(0, 9999);
            return userNames[sel] + num + domain;
        }

        private void readUserNames()
        {
            System.IO.StreamReader myFile =
                new System.IO.StreamReader("Usernames.txt");
            while (!myFile.EndOfStream)
            {
                String str = myFile.ReadLine();

                userNames.Add(str.Substring(0, str.IndexOf('@') - 0));
            }
        }

        private List<String> userNames = new List<string>();
        bool acntWritten = false;
        String email;
        String vin;

        private void button2_Click(object sender, EventArgs e)
        {
            accountsFile =  new StreamReader("KSR-Accounts.txt");
            try
            {
                int start = Convert.ToInt32(textBox1.Text);
                for (int i = 0; i < start; i++)
                {
                    accountsFile.ReadLine();
                }
            }
            catch (System.Exception)
            { }
            fileAccounts = true;
            clearCookies();
            nextLogin = true;
            webBrowser1.Navigate("http://www.keepsummerrolling.com/login");
        }
        bool fileAccounts = false;
        StreamReader accountsFile;
        Decaptcher decap;
        bool loginLoaded = false;
        bool lossLoaded = false;
        bool winLoaded = false;

        private void timer1_Tick(object sender, EventArgs e)
        {
            nextLogin = true;
            nextLose = false;
            webBrowser1.Navigate("http://www.keepsummerrolling.com/login");
        }
    }
}
